package esclient

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	elastic "github.com/elastic/go-elasticsearch/v8"
	"io"
	"listenboos-common/es/model"
	"log"
	"strings"
	"time"
)

type ESClient struct {
	Es *elastic.Client
}

func NewESClient() *ESClient {
	client, err := elastic.NewClient(elastic.Config{
		Addresses: []string{"http://192.168.2.9:9200"},
	})
	if err != nil {
		panic(err)
	}
	return &ESClient{Es: client}
}
func (s *ESClient) CreateIndex(indexName string, data []byte) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	// 创建index
	s.Es.Indices.Create.WithContext(ctx)
	res, err := s.Es.Index(indexName, bytes.NewReader(data))
	if err != nil && res.StatusCode != 200 {
		return err
	}
	return nil
}
func (s *ESClient) GetAlbumDocQuery(idexName string, query string) error {
	//ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	//defer cancel()
	res, err := s.Es.Search(
		s.Es.Search.WithIndex(idexName),
		s.Es.Search.WithBody(strings.NewReader(query)),
	)
	if err != nil && res.StatusCode != 200 {
		return err
	}
	body, _ := io.ReadAll(res.Body)
	var responseData LiveTagTest
	err = json.Unmarshal(body, &responseData)
	if err != nil {
		log.Fatalf("Error unmarshalling JSON: %v", err)
	}
	fmt.Printf("tag :%#v", responseData)
	return nil
}

func (s *ESClient) GetDocByTitle(idexName string, title string) error {
	//ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	//defer cancel()
	res, err := s.Es.Get(idexName, title)
	if err != nil && res.StatusCode != 200 {
		return err
	}
	body, _ := io.ReadAll(res.Body)
	var responseData LiveTagTest
	err = json.Unmarshal(body, &responseData)
	if err != nil {
		log.Fatalf("Error unmarshalling JSON: %v", err)
	}
	fmt.Printf("tag :%#v", responseData)
	return nil
}

type LiveTagTest struct {
	Id         int64  `json:"Id"`         // 编号
	Name       string `json:"Name"`       // 标签名称
	IconUrl    string `json:"IconUrl"`    // 标签图标url
	OrderNum   int64  `json:"OrderNum"`   // 排序
	CreateTime string `json:"CreateTime"` // 创建时间
	UpdateTime string `json:"UpdateTime"`
	IsDeleted  int64  `json:"IsDeleted"`
}

func (s *ESClient) CreateIndex2(indexName string, bytes []byte) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	resp, err := s.Es.Indices.Create(indexName,
		s.Es.Indices.Create.WithContext(ctx),
		s.Es.Indices.Create.WithBody(strings.NewReader(string(bytes))))
	if err != nil {
		fmt.Println("创建索引失败")
		return err
	}
	if resp.StatusCode == 200 {
		fmt.Println("创建索引成功")
	}
	return nil
}

//	func (s *ESClient) CreateIndex1() error {
//		ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
//		defer cancel()
//		// 这是一个链式调用，你可以通过链式调用来构造复杂请求。
//		// 重复创建会报错，所以你可以换一个名字
//		resp, err := s.Es.Indices.Create("user_idx_test",
//			s.Es.Indices.Create.WithContext(ctx),
//			s.Es.Indices.Create.WithBody(strings.NewReader(`
//
//	{
//	 "settings": {
//	   "number_of_shards": 3,
//	   "number_of_replicas": 2
//	 },
//	 "mappings": {
//	   "properties": {
//	     "email": {
//	       "type": "text"
//	     },
//	     "phone": {
//	       "type": "keyword"
//	     },
//	     "birthday": {
//	       "type": "date"
//	     }
//	   }
//	 }
//	}
//
// `)))
//
//		if err != nil {
//			fmt.Println("创建索引失败")
//			return err
//		}
//		if resp.StatusCode == 200 {
//			fmt.Println("创建索引成功")
//		}
//		return nil
//	}
func (s *ESClient) CreateStructIndex() error {
	//ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	//defer cancel()
	var albumInfo model.AlbumInfo
	albumInfo.AlbumTitle = "我是测试"
	albumInfo.Id = 1
	data, _ := json.Marshal(albumInfo)

	// 这是一个链式调用，你可以通过链式调用来构造复杂请求。
	// 重复创建会报错，所以你可以换一个名字
	//index, err := s.Es.Indices.Create("album_info_test")
	//if err != nil {
	//	fmt.Println(err)
	//	return err
	//}
	//fmt.Println(index)
	response, err := s.Es.Index("album_info_test", bytes.NewReader(data))
	fmt.Sprintf("response %s,error:%v", response, err)
	return nil
	//resp, err := s.Es.Indices.Create("user_idx_test",
	//	s.Es.Indices.Create.WithContext(ctx),
	//	s.Es.Indices.Create.WithBody(strings.NewReader(data))
}
func (s *ESClient) TestGetDoc() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	resp, err := s.Es.Search(s.Es.Search.WithContext(ctx),
		s.Es.Search.WithBody(strings.NewReader(`
{  
  "query": {  
    "range": {  
      "birthday": {
        "gte": "1990-01-01"
      }
    }  
  }  
}
`)))
	fmt.Sprintf("response %s,error:%v", resp, err)
}
